package com.digital.smartgrow.common.advice;

import com.digital.smartgrow.common.exception.MyException;
import com.digital.smartgrow.common.exception.TokenException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Comparator;
import java.util.stream.Collectors;

/**
 * 异常结果统一处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> exception(Exception e) {
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        String errMsg = e.getMessage();
        if (e.getMessage().contains("DateTimeParseException")) {
            errMsg = "时间格式错误";
        }
        return Result.fail(ReturnCode.RC500.getCode(), errMsg);
    }

    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    public Result<String> duplicateKeyException(Exception e) {
        log.error("数据库写入异常 ex={}", e.getMessage(), e);
        String field = e.getCause().toString().split("'")[3].toString().split("_")[1];
        String fieldStr = "其它字段";
        if (field.contains("id")) {
            fieldStr = "id";
        } else if (field.contains("number")) {
            fieldStr = "编码";
        }
        String msg = fieldStr + "冲突";
        return Result.fail(ReturnCode.RC999.getCode(), msg);
    }

    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> nullPointException(Exception e) {
        log.error("空指针异常 ex={}", e.getMessage(), e);
        return Result.fail(ReturnCode.RC500.getCode(), e.getMessage());
    }

    //swagger 参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String msg = bindingResult.getFieldErrors().stream().sorted(Comparator.comparing(FieldError::getField))
                .map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
        log.error("参数验证失败: {},", e.getMessage());
        return Result.fail(ReturnCode.RC400.getCode(), msg);
    }

    //自定义异常
    @ExceptionHandler(MyException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Object handleMyException(MyException e) {
        log.error("自定义异常: {},", e.getMessage(), e);
        return Result.fail(ReturnCode.RC400.getCode(), e.getMessage());
    }

    //token验证异常
    @ExceptionHandler(TokenException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Object handleTokenException(TokenException e) {
        return Result.fail(ReturnCode.INVALID_TOKEN.getCode(), e.getMessage());
    }

    //参数校验异常
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Object handleBindException(BindException e) {
        log.error("参数校验异常: {},", e.getMessage(), e);
        StringBuffer str = new StringBuffer();
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            ArgumentInvalidResult invalidArgument = new ArgumentInvalidResult();
            String code = error.getCode();
            invalidArgument.setCode(code);
            invalidArgument.setField(error.getField());
            String msg;
            if (code.equals("typeMismatch")) {
                msg = error.getField() + "类型错误";
            } else {
                msg = error.getDefaultMessage();
            }
            str.append(msg).append(",");
        }
        String er = str.toString();
        if (!er.equals("")) {
            er = er.substring(0, er.length() - 1);
        }
        return Result.fail(ReturnCode.RC400.getCode(), er);
    }
}
